package com.gt.gt_securitytest.config;


import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Resource
    TokenAuthorizationManager tokenAuthorizationManager;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //不使用jwt令牌
/*        http.authorizeHttpRequests((request)->request
                .requestMatchers("/security/admin").hasRole("ADMIN")
                .requestMatchers("/security/user").hasRole("USER")
                .anyRequest().authenticated());
        http.formLogin(Customizer.withDefaults());
        http.csrf(csrf->{csrf.disable();});*/


        //jwt令牌配置
        http.authorizeHttpRequests((request)->request
                .requestMatchers("/security/login").permitAll()
                .anyRequest().access(tokenAuthorizationManager));

        //关闭会话
        http.sessionManagement((session)->session.sessionCreationPolicy((SessionCreationPolicy.STATELESS)));
        //关闭缓存
        http.headers((header)->header.cacheControl((cache)->cache.disable()));
        // 关闭保护
        http.csrf(csrf->{csrf.disable();});

        return http.build();
    }
    //自定义的用户认证服务
    //获得AuthenticationManager实例
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }


    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
